package iloc.cc.tablelayoutdemo;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

	private TabLayout tabLayout;
	private ViewPager viewPager;
	private SimpleFragmentPagerAdapter adapter;

	private FragmentManager manager;

	private List<Fragment> list;
	private List<String> res;
	private String[] titles;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tabLayout = findViewById(R.id.tabLayout);
		viewPager = findViewById(R.id.viewPager);
		manager = getSupportFragmentManager();
		list = new ArrayList<>();
		res = new ArrayList<>();
		res.add("北京");
		res.add("深圳");
		res.add("上海");
		res.add("天津");


		titles = new String[res.size() + 5];
		for (int i = 0; i < res.size(); i++) {
			list.add(BranchListFragment.newInstance(res.get(i), res.get(i)));
			titles[i] = res.get(i);
		}


		adapter = new SimpleFragmentPagerAdapter(manager, list,
				titles);
		viewPager.setAdapter(adapter);
		viewPager.setOffscreenPageLimit(titles.length - 1);
		tabLayout.setupWithViewPager(viewPager);


	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.main_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.second_menu) {
			res.clear();
			list.clear();
			res.add("NewYork");
			res.add("Tokyo");
			res.add("Seoul");
			res.add("Singapore");
			res.add("Kuala Lumpur");

			for (int i = 0; i < res.size(); i++) {
				list.add(BranchListFragment.newInstance(res.get(i), res.get(i)));
				titles[i] = res.get(i);
			}

			adapter.setFragments(list);

			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
